/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package define;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

/**
 *
 * @author RoderickNestor
 */
public class CreateTpl {

    ProjectDefine project = null;

    public void process(String path_xml) {

        File file = new File(path_xml);
        if (!file.exists()) {
            System.err.println("Fichero XML no existe");
            //return null;
        }
        //leer xml
        InputStream is = null;
        Reader reader = null;
        try {
            is = new FileInputStream(path_xml);
            reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            System.out.println("Reding xml...");
        } catch (FileNotFoundException | UnsupportedEncodingException ex) {
            System.err.println("Error al leer fichero XML : " + ex);
        }
        //Poblar objecto Project        
        JAXBContext jc;
        try {
            jc = JAXBContext.newInstance(ProjectDefine.class);
            Unmarshaller u = jc.createUnmarshaller();
            project = (ProjectDefine) u.unmarshal(reader);
            System.out.println("Built project...");
        } catch (JAXBException ex) {
            System.err.println("Error al poblar objeto Project : " + ex.toString());
        }
    }

    public void createfile(String path) {
        try (PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(path)))) {
            System.out.println(path);
            pw.print("");
            pw.close();
        } catch (IOException ex) {
            Logger.getLogger(CreateTpl.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void create_tpl(String path) {
        for (ClassDefine cls_def : project.list) {
            for (TemplateDefine tpl_def : cls_def.templates) {
                File file = new File(path + tpl_def.path);
                if (!file.exists()) {
                    createfile(path + tpl_def.path);
                }
            }
            for (PartialDefine ptl_def : cls_def.partials) {
                File file = new File(path + ptl_def.path);
                if (!file.exists()) {
                    createfile(path + ptl_def.path);
                }
            }
        }
    }

}
